package com.leetcode;

import java.util.Stack;

/**
 * 用两个栈实现一个队列。队列的声明如下，请实现它的两个函数 appendTail 和 deleteHead ，
 * 分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素，deleteHead 操作返回 -1 )
 *
 * 输入：
 * ["CQueue","appendTail","deleteHead","deleteHead"]
 * [[],[3],[],[]]
 * 输出：[null,null,3,-1]
 *
 * 输入：
 * ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
 * [[],[],[5],[2],[],[]]
 * 输出：[null,-1,null,null,5,2]
 *
 * 解题思路：
 *  1、栈A负责入站
 *  2、栈B负责出栈，如果栈B为空，先把栈A的数据依次弹出在入栈，然后进行弹出
 */
public class Offer09 {
    public static void main(String[] args) {
        CQueue cQueue = new CQueue();
        // TODO 1,2,3,4,5,6,7
        for (int i = 0; i < 7; i++) {
            cQueue.appendTail(i);
        }

        // TODO 弹出1
        System.out.println("弹出0 = " + cQueue.deleteHead());
        // TODO 入队列8
        System.out.println("入队列7");
        cQueue.appendTail(7);
        // TODO 弹出1，2，3，4，5，6，7
        System.out.println("弹出1 = " + cQueue.deleteHead());
        System.out.println("弹出2 = " + cQueue.deleteHead());
        System.out.println("弹出3 = " + cQueue.deleteHead());
        System.out.println("弹出4 = " + cQueue.deleteHead());
        System.out.println("弹出5 = " + cQueue.deleteHead());
        System.out.println("弹出6 = " + cQueue.deleteHead());
        System.out.println("弹出7 = " + cQueue.deleteHead());
        // TODO 没有元素弹出-1
        System.out.println("没有元素 = " + cQueue.deleteHead());

    }
}

class CQueue {
    private Stack<Integer> astack;

    private Stack<Integer> bstack;

    public CQueue() {
        astack = new Stack<>();
        bstack = new Stack<>();
    }

    /**
     * 入队列
     * @param tmp
     */
    public void appendTail(Integer tmp) {
        astack.push(tmp);
    }

    /**
     * 出队列
     */
    public int deleteHead() {
        if (bstack.isEmpty()) {
            // TODO 从a栈入数据过来
            while (!astack.isEmpty()) {
                bstack.push(astack.pop());
            }
        }

        if (bstack.isEmpty()) {
            return -1;
        }
        else {
            return bstack.pop();
        }
    }
}


